import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件
import login from '../views/user/login.vue'
import home from '../views/home/home.vue'
import user from '../views/user/user.vue'
import qa from '../views/qa/qa.vue'
import move from '../views/move/move.vue'
import notfound from '../views/notfount/notfound.vue'
import edit from '../views/edit/edit.vue'
import article from '../views/home/article.vue'
import search from '../views/home/search.vue'
import searchResult from '../views/home/searchResult.vue'
import xiaozhi from '../views/xiaozhi/xiaozhi.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    name: 'login',
    path: '/login',
    component: login,
    meta: {
      hideTab: true
    }
  },
  {
    path: '/home',
    name: 'home',
    component: home,
    meta: { showTab: true }
  },
  {
    path: '/qa',
    name: 'qa',
    component: qa,
    meta: { showTab: true }
  },
  {
    path: '/move',
    name: 'move',
    component: move,
    meta: { showTab: true }
  },
  {
    path: '/user',
    name: 'user',
    component: user,
    meta: { showTab: true, isLogin: true }
  },
  {
    path: '/notfound',
    name: 'notfound',
    component: notfound,
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit,
  },
  {
    path: '/article',
    name: 'myarticle',
    component: article,
  },
  {
    path:'/searchResult',
    name:'searchResult',
    component:searchResult
  },
  {
    path: '/xiaozhi',
    name:'xiaozhi',
    component:xiaozhi
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '*',
    redirect: '/notfound'
  },

]

/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
//(1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
//(2)替换原型链中的push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    //originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  //如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /*
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

// 注册导航守卫
import { getToken } from '@/utils/token'
router.beforeEach((to, from, next) => {
  // console.log(getToken);
  if (to.meta.isLogin && !getToken()) {
    // 没有登录,跳转登入页
    next({ path: '/login' })
  } else {
    next()
  }
})
